<?php
/**
 * Created by PhpStorm.
 * User: yui
 * Date: 2017/3/31
 * Time: 0:50
 */

namespace common\services;

use common\library\comFun;
use common\models\MemberLogin;
use common\models\MemberRegister;
use common\models\MemberResetPwd;
use common\models\MemberSmsLogin;
use Yii;
use common\models\Member;

class MemberSve extends BaseSve
{
    /**
     * 后台更新
     * @param array $data
     * @param string $scenario //场景
     * @return array
     */
    public function update(array $data, string $scenario = ''):array
    {
        if(empty($data['password'])){
            unset($data['password']);
        }else{
            $data['password'] = Yii::$app->security->generatePasswordHash($data['password']);
        }
        return parent::update($data);
    }

    /**
     * 添加、注册
     * @param array $data
     * @param string $scenario //场景
     * @return array
     */
    public function add(array $data, string $scenario = ''):array
    {
        try {
            //获取各个层级的id
            $PersonnelClassSve = new PersonnelClassSve();
            $roleArr = $PersonnelClassSve->getRole($data['role']);
            $data['parent_role'] = $roleArr['parent_role'];
            $data['ancestors_role'] = $roleArr['ancestors_role'];
            $MemberRegister = new MemberRegister();
            //加载数据到注册模型
            $MemberRegister->load(['MemberRegister' => $data]);
            //验证
            self::checkErr($MemberRegister);

            //验证短信
            /*
            $AliSmsSve = new AliSmsSve();
            $rs = $AliSmsSve->checkVerifyCode($MemberRegister->mobile, 'register', $MemberRegister->verify_code);
            if ($rs['code'] !== 0) {
                throw new \Exception($rs['msg'], -1);
            }*/




            //加载数据到用户模型
            $Member = new Member();
            $Member->load(['Member' => $MemberRegister->toArray()]);
            $Member->invitation_code = comFun::createRandom(6);
            $Member->register_time = $_SERVER['REQUEST_TIME'];
            //验证
            self::checkErr($Member);
            //加密密码
            $Member->setPassword($Member->password);
            $rs = $Member->save();
            if ($rs === true) {
                return self::result('注册成功', 0);
            } else {
                throw new \Exception('注册失败', -1);
            }
        } catch (\Exception $e) {
            if (array_key_exists($e->getCode(), OC_ERR_CODE)) {
                return self::result($e->getMessage(), $e->getCode());
            } else {
                return self::result('系统繁忙', -50);
            }
        }
    }

    /**
     * 登录
     * @param array $data
     * @return array
     */
    public function login(array $data):array
    {
        try {
            $MemberLogin = new MemberLogin();
            $MemberLogin->load(['MemberLogin' => $data]);
            //验证账号密码
            self::checkErr($MemberLogin);

            //获取对象
            $Member = $MemberLogin->getMember();
            if($Member->status == 0 || $Member->is_del == 1 ){
                throw new \Exception('用户禁止登陆', -1);
            }
            //如果token存在,获取缓存对象
            $cache = Yii::$app->cache;
            if ($Member->token) {
                $cacheMemberObj = $cache->get($Member->token);
            }
            //如果token不存在，或者token过期
            if (empty($Member->token) || empty($cacheMemberObj)) {
                //新建token
                $Member->generateToken();
                //更新到数据库
                $rs = $this->update([
                    'member_id' => $Member->member_id,
                    'first_login_time' => empty($Member->first_login_time) ? $_SERVER['REQUEST_TIME'] : $Member->first_login_time,
                    'old_login_time' => $Member->login_time,
                    'login_time' => $_SERVER['REQUEST_TIME'],
                    'old_login_ip' => $Member->login_ip,
                    'login_ip' => Yii::$app->request->getUserIP(),
                    'token' => $Member->token
                ]);
                if ($rs === false) {
                    throw new \Exception('登录失败', -1);
                }
            }
            //缓存用户对象
            if ($cache->set($Member->token, $Member, OC['session_lifetime'])) {
                return self::result('登录成功', 0, ['token' => $Member->token, 'mobile' => $Member->mobile]);
            } else {
                throw new \Exception('登录失败', -1);
            }
        } catch (\Exception $e) {echo  $e->getMessage();
            if (array_key_exists($e->getCode(), OC_ERR_CODE)) {
                return self::result($e->getMessage(), $e->getCode());
            } else {
                return self::result('系统繁忙', -50);
            }
        }
    }

    /**
     * 登录
     * @param array $data
     * @return array
     */
    public function loginBySms(array $data):array
    {
        try {
            $MemberSmsLogin = new MemberSmsLogin();
            $MemberSmsLogin->load(['MemberSmsLogin' => $data]);
            //验证账号密码
            self::checkErr($MemberSmsLogin);
            //获取对象
            $Member = $MemberSmsLogin->getMember();
            //如果token存在,获取缓存对象
            $cache = Yii::$app->cache;
            if ($Member->token) {
                $cacheMemberObj = $cache->get($Member->token);
            }
            //如果token不存在，或者token过期
            if (empty($Member->token) || empty($cacheMemberObj)) {
                //新建token
                $Member->generateToken();
                //更新到数据库
                $rs = $this->update(['member_id' => $Member->member_id, 'token' => $Member->token]);
                if ($rs === false) {
                    throw new \Exception('登录失败', -1);
                }
            }
            //缓存用户对象
            if ($cache->set($Member->token, $Member, OC['session_lifetime'])) {
                return self::result('登录成功', 0, ['token' => $Member->token, 'mobile' => $Member->mobile]);
            } else {
                throw new \Exception('登录失败', -1);
            }
        } catch (\Exception $e) {
            if (array_key_exists($e->getCode(), OC_ERR_CODE)) {
                return self::result($e->getMessage(), $e->getCode());
            } else {
                return self::result('系统繁忙', -50);
            }
        }
    }

    /**
     * 会员退出
     * @return array
     */
    public function logout($token)
    {
        try {
            if (Yii::$app->cache->delete($token)) {
                return self::result('退出成功', 0);
            } else {
                return self::result('退出失败');
            }
        } catch (\Exception $e) {
            return self::result('系统繁忙', -50);
        }
    }

    /**
     * 修改密码
     * @param array $data
     * @return array
     */
    public function resetPwd(array $data,$member)
    {
        try {
            //获取对象
            $Member = Member::findByMobile($member->mobile);
            $MemberResetPwd = new MemberResetPwd();
            $MemberResetPwd->_old_password = $member->password;
            $MemberResetPwd->load(['MemberResetPwd' => $data]);
            //验证账号密码
            self::checkErr($MemberResetPwd);
            $Member->setPassword($MemberResetPwd->password);
            $rs = $Member->update();
            if ($rs !== false) {
                return self::result('修改成功', 0);
            } else {
                throw new \Exception('修改失败', -1);
            }
        } catch (\Exception $e) {
          //  if (array_key_exists($e->getCode(), OC_ERR_CODE)) {
                return self::result($e->getMessage(), $e->getCode());
            //} else {
            //    return self::result('系统繁忙', -50);
            //}
        }
    }


    /**
     * 获取用户列表 BY:lihouse
     * @param array $where
     * @param string $orderBy
     * @param bool $isPaging
     * @return array
     */
    public function getList($where = [], string $orderBy = '', bool $isPaging = false):array
    {
        $tmpwhere = $where;
        $request = Yii::$app->request;
        $where = ['and'];
        //插入昵称查询条件
        $nickname = $request->get('nickname');
        if ($nickname) {
            array_push($where, ['like', 'nickname', $nickname]);
        }
        //插入城市查询条件
        $cityId = $request->get('city_id');
        if ($cityId) {
            array_push($where, ['=', 'city_id', $cityId]);
        }
        //插入角色查询条件
        $role = $request->get('role');
        if ($role) {
            array_push($where, ['=', 'role', $role]);
        }

        //插入电话号码查询条件
        $mobile = $request->get('mobile');
        if ($mobile) {
            array_push($where, ['like', 'mobile', $mobile]);
        }
        //插入额外查询条件
        foreach ($tmpwhere as $item) {
            if (is_array($item)) {
                array_push($where, $item);
            } else {
                return self::result('插入额外查询条件错误');
            }
        }
        return parent::getList($where, $orderBy, $isPaging);
    }


    public function getRoleList($where = [], string $orderBy = '', bool $isPaging = false):array
    {

        return parent::getList($where, $orderBy, $isPaging);
    }


    //TODO 修改个人信息
    public function updateBySelf($data)
    {
        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();
        $MemberSve = new MemberSve();
        $WorksSve = new WorksSve();
        try {
            $memberRs = $MemberSve->getInfo(['member_id' => $data['member_id'], 'is_del' => 0]);
            if ($memberRs['code'] !== 0) {
                throw new \Exception('找不到该用户', -1);
            }
            $MemberObj = $memberRs['data']['Obj'];
            //判断用户角色（如果是糕手，修改地区就要更新作品的地区信息，如果不修改就不修改）
            if ($MemberObj['role'] === 1) {
                //修改地区
                if (isset($data['province_id']) && isset($data['city_id']) && isset($data['area_id'])) {
                    //更新作品地区信息
                    $worksListRs = $WorksSve->getList(['=', 'member_id', $MemberObj['member_id']]);
                    if ($worksListRs['code'] === 0) {
                        foreach ($worksListRs['data']['list'] as $WorksObj) {
                            $WorksObj['province_id'] = $data['province_id'];
                            $WorksObj['city_id'] = $data['city_id'];
                            $WorksObj['area_id'] = $data['area_id'];
                            $rs = $WorksObj->update();
                            if ($rs === false) {
                                throw new \Exception('作品地区更新失败', -1);
                            }
                        }
                    }
                } else if (!isset($data['province_id']) && !isset($data['city_id']) && !isset($data['area_id'])) { //全不修改

                } else {
                    throw new \Exception('缺少地区信息', -1);
                }
                if ($data['address']) {
                    throw new \Exception('具体地点不能为空', -1);
                }
            }
            $MemberObj->load(['Member' => $data]);
            self::checkErr($MemberObj);
            $rs = $MemberObj->update();
            if ($rs === false) {
                throw new \Exception('更新失败', -1);
            }
            $transaction->commit();
            return self::result('更新成功', 0);
        } catch (\Exception $e) {
            $transaction->rollBack();
            if (array_key_exists($e->getCode(), OC_ERR_CODE)) {
                return self::result($e->getMessage(), $e->getCode());
            } else {
                return self::result('系统繁忙', -50);
            }
        }
    }


    /**
     * 角色正文 BY:lihouse
     * @return array
     */
    public function roleZH()
    {
        return [
            0 => '普通会员',
            1 => '蛋糕手',
            10 => '前台编辑员'
        ];
    }
}